﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using DataLib.Common;
using DataLib.Accounts.Bus;
using DataLib.Accounts.Data;
using DataLib.Model;

namespace Ewts.Project
{
    public partial class ServerPoint : System.Web.UI.Page
    {
        string alreadySPName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Session["UserInfo"] == null)
                {
                    Response.Redirect("/Accounts/Login.aspx");
                }
                GetDetile();
                getDropDown();
                getCheckBox();
                if (!string.IsNullOrEmpty(Request.QueryString["ServerPointID"]))
                {
                    BindUpdateInfo();
                }
                else
                {
                    getGrid();
                }
            }
        }

        /// <summary>
        /// 得到界面明细
        /// </summary>
        private void GetDetile()
        {
            int id = 0;
            if (Request["id"] != null && Request["id"].ToString().Trim() != "")
            {
                id = int.Parse(Request["id"].ToString());
            }
            DataLib.Model.ServerArea sModel = new DataLib.Model.ServerArea();
            DataLib.BLL.ServerArea sBll = new DataLib.BLL.ServerArea();
            sModel = sBll.GetModel(id);
            if (sModel != null)
            {
                this.lblAreaName.Text = sModel.AreaName.ToString();
            }

        }
        /// <summary>
        /// 绑定修改信息
        /// </summary>
        private void BindUpdateInfo()
        {
            int pointid = Convert.ToInt32(Request.QueryString["ServerPointID"].ToString());
            DataLib.BLL.ServerPoint sBll = new DataLib.BLL.ServerPoint();
            DataLib.Model.ServerPoint smodel = new DataLib.Model.ServerPoint();
            smodel = sBll.GetModel(pointid);
            SetChecked(smodel.LookSalesmanTrueName, '@');
            this.dropcjosalesman.SelectedItem.Text = smodel.CjopersonTrueName;
            this.droporderperson.SelectedItem.Text = smodel.PowerpersonTrueName;
            this.serverPoint.SelectedItem.Text = smodel.ServerPointName;
            this.Button1.Text = "保存";
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            int id = 0;
            if (Request["id"] != null && Request["id"].ToString().Trim() != "")
            {
                id = int.Parse(Request["id"].ToString());
            }
            if (!string.IsNullOrEmpty(Request.QueryString["ServerPointID"]))
            {
                int pointid = Convert.ToInt32(Request.QueryString["ServerPointID"].ToString());
                DataLib.BLL.ServerPoint sBll = new DataLib.BLL.ServerPoint();
                DataLib.Model.ServerPoint smodel = new DataLib.Model.ServerPoint();
                smodel = sBll.GetModel(pointid);
                smodel.LookSalesmanUserName = GetSplitChecked(chksalesman, "@", "head");
                smodel.LookSalesmanTrueName = GetSplitChecked(chksalesman, "@", "foot");
                DataLib.Accounts.Data.User uBll = new DataLib.Accounts.Data.User();
                DataSet dtcjo = uBll.GetUserList(this.dropcjosalesman.SelectedItem.Text.ToString(), "");
                if (dtcjo != null)
                {
                    smodel.CjopersonUserName = dtcjo.Tables[0].Rows[0]["UserName"].ToString();
                }
                smodel.CjopersonTrueName = this.dropcjosalesman.SelectedItem.Text;
                DataSet dtpower = uBll.GetUserList(this.droporderperson.SelectedItem.Text.ToString(), "");
                if (dtpower != null)
                {
                    smodel.PowerpersonUserName = dtpower.Tables[0].Rows[0]["UserName"].ToString();
                }
                smodel.PowerpersonTrueName = this.droporderperson.SelectedItem.Text;
                smodel.ServerPointName = this.serverPoint.SelectedItem.Text;
                sBll.Update(smodel);
                DataLib.BLL.Project pBll = new DataLib.BLL.Project();
                pBll.updatelist(this.serverPoint.SelectedItem.Text, "ProjectsRelation", " where ServerPointID =" + pointid.ToString(), "ServerPointName");
                Response.Redirect("ServerPoint.aspx?id=" + id.ToString());
            }
            else
            {
                string salesUserName = GetSplitChecked(chksalesman, "@", "head");
                string salesman = GetSplitChecked(chksalesman, "@", "foot");
                //string serverPoint = GetChecked(chkserverpoint, "@");
                string serverPoint = this.serverPoint.SelectedItem.Text.ToString();
                DataLib.Model.ServerPoint sModel = new DataLib.Model.ServerPoint();
                DataLib.BLL.ServerPoint sBll = new DataLib.BLL.ServerPoint();
                DataLib.Model.ServerArea aModel = new ServerArea();
                DataLib.BLL.ServerArea aBll = new DataLib.BLL.ServerArea();
                aModel = aBll.GetModel(id);
                if (aModel != null)
                {
                    sModel.ServerAreaID = id;
                    sModel.AreaName = aModel.AreaName;
                }


                DataLib.Accounts.Data.User uBll = new DataLib.Accounts.Data.User();

                sModel.LookSalesmanTrueName = salesman;
                sModel.LookSalesmanUserName = salesUserName;

                sModel.PowerpersonTrueName = this.droporderperson.SelectedItem.Text.ToString();
                DataSet dt = uBll.GetUserList(this.droporderperson.SelectedItem.Text.ToString(), "");
                if (dt != null)
                {
                    sModel.PowerpersonUserName = dt.Tables[0].Rows[0]["UserName"].ToString();
                }
                sModel.CjopersonTrueName = this.dropcjosalesman.SelectedItem.Text.ToString();
                DataSet dt1 = uBll.GetUserList(this.dropcjosalesman.SelectedItem.Text.ToString(), "");
                if (dt1 != null)
                {
                    sModel.CjopersonUserName = dt1.Tables[0].Rows[0]["UserName"].ToString();
                }
                sModel.ServerPointName = serverPoint;
                sModel.CreateTime = DateTime.Now;
                if (Session["UserInfo"] != null)
                {
                    DataLib.Accounts.Bus.User curUser = new DataLib.Accounts.Bus.User();
                    curUser = (DataLib.Accounts.Bus.User)Session["UserInfo"];
                    sModel.CreateMan = curUser.UserName;
                }
                sBll.Add(sModel);
                getGrid();
                getCheckBox();
            }
        }

        private void getGrid()
        {
            int id = 0;
            if (Request["id"] != null && Request["id"].ToString().Trim() != "")
            {
                id = int.Parse(Request["id"].ToString());
            }
            string strwhere = "IsDel = 0 and ServerAreaID = " + id + " ";
            DataLib.BLL.ServerPoint sBll = new DataLib.BLL.ServerPoint();
            DataTable dt = sBll.GetList(strwhere).Tables[0];
            this.rept.DataSource = dt;
            this.rept.DataBind();
        }

        /// <summary>
        /// 绑定checkbox
        /// </summary>
        private void getCheckBox()
        {
            //业务员
            string str = " 1=1 and department = '市场部'";
            //FUND.DataLib.BLL.fund_goodsclass gBll = new FUND.DataLib.BLL.fund_goodsclass();
            //this.chksalesman.DataSource = gBll.GetList(str);
            DataLib.Accounts.Data.User uBll = new DataLib.Accounts.Data.User();
            this.chksalesman.DataSource = uBll.getUserList(str);
            this.chksalesman.DataValueField = "UserID";
            this.chksalesman.DataTextField = "UTName";
            this.chksalesman.DataBind();

            //服务点
            int id = 0;
            if (Request["id"] != null && Request["id"].ToString().Trim() != "")
            {
                id = int.Parse(Request["id"].ToString());
            }
            string strwhere = "IsDel = 0 and ServerAreaID = " + id.ToString();
            if (!string.IsNullOrEmpty(Request.QueryString["ServerPointID"]))
            {
                int pointid = Convert.ToInt32(Request.QueryString["ServerPointID"].ToString());
                DataLib.BLL.ServerPoint seBll = new DataLib.BLL.ServerPoint();
                DataLib.Model.ServerPoint smodel = new DataLib.Model.ServerPoint();
                smodel = seBll.GetModel(pointid);
                strwhere = string.Format("IsDel = 0 and ServerAreaID = {0} and ServerPointName <> '{1}' ", id.ToString(),smodel.ServerPointName);
            }
            DataLib.BLL.ServerPoint sBll = new DataLib.BLL.ServerPoint();
            DataTable dt = sBll.GetList(strwhere).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    alreadySPName += dr["ServerPointName"].ToString() + "@";
                }
            }
            string deletespname = "";
            if(alreadySPName != "")
            {
                string[] spnames = alreadySPName.Split('@');
                for (int i = 0; i < spnames.Length; i++)
                {
                    if (spnames[i] != "")
                    {
                        deletespname += string.Format("'{0}'", spnames[i]) + ",";
                    }
                }
                deletespname = deletespname.Substring(0, deletespname.Length - 1);
            }
            string strWhere = " libType = '归属地' ";
            if (deletespname != "")
            {
                deletespname = string.Format("({0})", deletespname);
                strWhere = " libType = '归属地' and libValue not in " + deletespname;
            }
            DataLib.BLL.Sys_Library slBll = new DataLib.BLL.Sys_Library();
            this.serverPoint.DataSource = slBll.GetList(strWhere);
            this.serverPoint.DataValueField = "id";
            this.serverPoint.DataTextField = "libValue";
            this.serverPoint.DataBind();

        }

        /// <summary>
        /// 绑定下拉列表
        /// </summary>
        private void getDropDown()
        {
            string str = " 1=1 and department = '市场部' ";
            DataLib.Accounts.Data.User uBll = new DataLib.Accounts.Data.User();
            this.dropcjosalesman.DataSource = uBll.getUserList(str);
            this.dropcjosalesman.DataValueField = "UserID";
            this.dropcjosalesman.DataTextField = "TrueName";
            this.dropcjosalesman.DataBind();

            string strWhere = " 1=1 and department = '市场部'";
            this.droporderperson.DataSource = uBll.getUserList(strWhere);
            this.droporderperson.DataValueField = "UserID";
            this.droporderperson.DataTextField = "TrueName";
            this.droporderperson.DataBind();
        }


        /// <summary>
        /// 得到chk选中的值
        /// </summary>
        /// <param name="checkList"></param>
        /// <param name="separator">分隔符</param>
        /// <returns></returns>
        public string GetChecked(CheckBoxList chkList, string separator)
        {
            string selval = "";
            foreach (System.Web.UI.WebControls.ListItem chk in chkList.Items)
            {
                if (chk.Selected == true)
                {
                    selval += chk.Text + separator;
                }
            }
            return selval;
        }
        /// <summary>
        /// 按照头或者尾截取控件的文本值
        /// </summary>
        /// <param name="chkList">操作的控件ID</param>
        /// <param name="separator">截取后用什么符号分隔</param>
        /// <param name="splitType">head为截取头部，foot为截取尾部</param>
        /// <returns></returns>
        public string GetSplitChecked(CheckBoxList chkList, string separator,string splitType)
        {
            string selval = "";
            foreach (System.Web.UI.WebControls.ListItem chk in chkList.Items)
            {
                if (chk.Selected == true)
                {
                    string[] mytext = chk.Text.Split('/');
                    if (splitType == "head")
                    {
                        selval += mytext[0] + separator;
                    }
                    else
                    {
                        selval += mytext[1] + separator;
                    }
                }
            }
            return selval;
        }
        /// <summary>
        /// 删除服务点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnDel_Click(object sender, CommandEventArgs e)
        {
            int ServerPointID = Convert.ToInt32(e.CommandName);
            new DataLib.BLL.ProjectsRelation().RelationDelete(0,ServerPointID, 0, 0, 2);
            getCheckBox();
            getGrid();
        }
        /// <summary>
        /// 初始化CheckBoxList中哪些是选中了的
        /// </summary>
        /// <param name="selval">选中了的值串例如："0,1,1,2,1"</param>
        /// <param name="separator">值串中使用的分割符例如"0,1,1,2,1"中的逗号</param> 
        public void SetChecked(string selval, char separator)
        {
            string[] arr = selval.Split(separator);
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] != null)
                {
                    foreach (System.Web.UI.WebControls.ListItem chk in chksalesman.Items)
                    {
                        if (chk.Text.Substring(chk.Text.IndexOf('/') + 1) == arr[i])
                        {
                            chk.Selected = true;
                        }
                    }
                }
            }
        }
    }
}